const ProductService =require('../../services/admin/ProductService.js')
const dayjs = require('dayjs')
const path =require('path')
const fs =require('fs')
const ProductController={
    
    AddProduct:async (req,res)=>{
            let now = dayjs()
            const nowTime = now.format('YYYY-MM-DD HH:mm:ss')
          const data=req.body
          const params=[]
          data.cover ='/productavator/'+req.file.filename
          data.editTime =nowTime
          for(let key in data )
           params.push(data[key])
           const result =await ProductService.AddProduct(params)
  
           if(result.code==400){
            res.send({
                code:400,
                result:result.err,
                msg:'添加产品失败'
            })
        }
        else{
            res.send({
                code:200,
                msg:'添加产品成功'
            })
        }
         },
    GetAllProduct:async (req,res)=>{
          const result = await ProductService.GetAllProduct()
          if(result.code==400){
            res.send({
                code:400,
                result:result.err,
                msg:'获取产品列表失败'
            })
        }
            else{
                res.send({
                    code:200,
                    result:result,
                    msg:'获取产品列表成功'
                })
            }
    },
    EditProduct:async (req,res)=>{
        let now = dayjs()
        const nowTime = now.format('YYYY-MM-DD HH:mm:ss')
         const data=req.body
         data.editTime=nowTime
        if(req.file){
         fs.unlink(path.resolve('public'+req.body.cover),(err)=>{
            if(err)
                console.log('删除失败',err);
             })
             data.cover='/productavator/'+req.file.filename
         }
    
         const result = await ProductService.EditProduct(data)
        if(result.code==400){
            res.send({
                code:400,
                result:result.err,
                msg:'产品编辑失败'
            })
        }
        else{
            res.send({
                code:200,
                msg:'产品编辑成功'
                    })
                }
        },

        Deleteproduct:async (req,res)=>{
           const result =await ProductService.Deleteproduct(req.body.id)
           if(result.code==400){
            res.send({
                code:400,
                result:result.err,
                msg:'删除失败'
            })
        }
        else{
            fs.unlink(path.resolve('public'+req.body.cover),(err)=>{
                if(err)
                    console.log(err);
            })
            res.send({
                code:200,
                msg:'删除成功'
                    })
                }
        },

}


module.exports=ProductController